package com.dxf.sysadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxf.common.utils.ResultJson;
import com.dxf.sysadmin.entity.*;
import com.dxf.sysadmin.entity.qo.MyPage;
import com.dxf.sysadmin.mapper.StudentMapper;
import com.dxf.sysadmin.service.ClazzService;
import com.dxf.sysadmin.service.StudentService;
import com.dxf.sysadmin.service.SysUserService;
import com.dxf.sysadmin.utils.ExcelAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生表 服务实现类
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    ClazzService clazzService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BCryptPasswordEncoder encoder;

    /**
     *学生列表分页查询
     */
    @Override
    public ResultJson studentPage(MyPage qry) {
        Page<Student> page = new Page<>(qry.getPage(), qry.getLimit());

        IPage<Student> iPage = page(page);
        Map<String, Object> map = new HashMap<>();
        map.put("rows",iPage.getRecords());
        map.put("total",iPage.getTotal());
        return ResultJson.ok().data(map);
    }

    /**
     *更具id列表删除学生
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson deleteStudent(List<Long> list) {
        removeByIds(list);
        //TODO
        return ResultJson.ok();
    }

    /**
     *新增或者更新学生
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson saveOrUpdateStudent(Student obj) {
        SysUser sysUser = new SysUser();
        if(obj.getId()!=null){
            sysUser.setId(obj.getUserId());
            sysUser.setName(obj.getName());
            sysUser.setAccount(obj.getStudentNo());
            sysUserService.updateById(sysUser);
        }else {
            sysUser.setStatus(0);
            sysUser.setName(obj.getName());
            sysUser.setAccount(obj.getStudentNo());
            sysUser.setPassword(encoder.encode(obj.getStudentNo()));
            sysUserService.save(sysUser);
            obj.setUserId(sysUser.getId());
        }
        saveOrUpdate(obj);
        return ResultJson.ok();
    }

    /**
     *下拉选项数据（班级，系统用户）
     */
    @Override
    public ResultJson selectData() {
        List<Clazz> clazzes = clazzService.list();
        List<SysUser> users = sysUserService.list();
        return ResultJson.ok().data("clazzes",clazzes).data("users",users);
    }

    /**
     *根据上传的excel插入学生
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson uploadFile(MultipartFile file) {
        //解析excel文件
        List<ArrayList<String>> row = ExcelAnalysis.analysis(file);
        List<SysUser> sysUsers=new ArrayList<>();
        List<Student> students=new ArrayList<>();
        //添加系统账号
        for (int i = 0;i<row.size();i++){
            List<String> cell = row.get(i);
            SysUser sysUser = new SysUser();
            sysUser.setStatus(0);
            Student student = new Student();
            for (int j = 0;j<cell.size();j++){
                if (j==0){
                    sysUser.setName(cell.get(j));
                    student.setName(cell.get(j));
                }else if (j==1){
                    sysUser.setAccount(cell.get(j));
                    sysUser.setPassword(encoder.encode(cell.get(j)));
                    student.setStudentNo(cell.get(j));
                }else if (j==2){
                    student.setClazzId(selectClazzId(cell.get(j)));
                }
            }
            sysUsers.add(sysUser);
            students.add(student);
        }
        sysUserService.saveBatch(sysUsers);
        for (int k = 0; k < sysUsers.size(); k++) {
            students.get(k).setUserId(sysUsers.get(k).getId());
        }
        saveBatch(students);
        return ResultJson.ok();
    }

    /**
     *获取班级id
     */
    private  Long selectClazzId(String clazzCode){
        List<Clazz> clazzes = clazzService.list(new QueryWrapper<Clazz>()
                .lambda().eq(Clazz::getCode, clazzCode));
        if (clazzes.size()!=0){
            return clazzes.get(0).getId();
        }else {
            Clazz clazz = new Clazz();
            clazz.setCode(clazzCode);
            clazz.setName(clazzCode+"班");
            clazzService.save(clazz);
            return clazz.getId();
        }
    }
}
